package ltd.hxya.novel.springsecurity.config;

import ltd.hxya.novel.springsecurity.filter.AuthorizeFilter;
import ltd.hxya.novel.springsecurity.handler.AuthenticationHandler;
import ltd.hxya.novel.springsecurity.handler.AuthorizeHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
public class SecurityWebConfig extends WebSecurityConfigurerAdapter {


    @Autowired
    private AuthorizeFilter authorizeFilter;
    /**
     * 使用PassWordEncode
     */
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf()
                .disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers("user/**").authenticated()
                .antMatchers("api/user/**").authenticated()
                .antMatchers("*/admin/**").authenticated()
                .anyRequest().permitAll();
        http.cors();
        //http.formLogin().disable();
        http.addFilterBefore(authorizeFilter,UsernamePasswordAuthenticationFilter.class);

        http.exceptionHandling().authenticationEntryPoint(new AuthenticationHandler());
        http.exceptionHandling().accessDeniedHandler(new AuthorizeHandler());

    }


    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}
